package com.cloud.gateway.config;

import cn.dev33.satoken.same.SaSameUtil;
import com.cloud.common.core.constant.CommonConstants;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * Author:  xuanning
 * Date:    2023/3/23 15:49
 */
@Configuration
public class ForwardFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String traceId=UUID.randomUUID().toString().replaceAll("-","");
        ServerHttpRequest newRequest = exchange
                .getRequest()
                .mutate()
                // 为请求追加 Same-Token 参数
                .header(SaSameUtil.SAME_TOKEN, SaSameUtil.getToken())
                .header(CommonConstants.traceId,traceId)
                .build();
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        return chain.filter(newExchange).then(Mono.fromRunnable(()->{
            ServerHttpResponse response=exchange.getResponse();
            response.getHeaders().add(CommonConstants.traceId,traceId);
        }));
    }
}
